﻿@page "/pages/documents"
@attribute [Authorize(Policy = Permissions.Documents.View)]
@using CleanArchitecture.Blazor.Application.Features.Documents.DTOs
@using CleanArchitecture.Blazor.Application.Features.Documents.Mappers
@using CleanArchitecture.Blazor.Application.Features.Documents.Queries.GetFileStream
@using CleanArchitecture.Blazor.Application.Features.Documents.Queries.PaginationQuery
@using CleanArchitecture.Blazor.Application.Features.Documents.Specifications
@using CleanArchitecture.Blazor.Domain.Common.Enums
@using BlazorDownloadFile
@using CleanArchitecture.Blazor.Server.UI.Hubs
@using CleanArchitecture.Blazor.Server.UI.Pages.Documents.Components
@using CleanArchitecture.Blazor.Application.Features.Documents.Caching
@using CleanArchitecture.Blazor.Application.Features.Documents.Commands.AddEdit
@using CleanArchitecture.Blazor.Application.Features.Documents.Commands.Delete
@implements IDisposable
@inject IBlazorDownloadFileService BlazorDownloadFileService
@inject HubClient Client
@inject IStringLocalizer<Documents> L

<PageTitle>@Title</PageTitle>

<MudDataGrid ServerData="@(new Func<GridState<DocumentDto>, Task<GridData<DocumentDto>>>(ServerReload))"
             FixedHeader="true"
             FixedFooter="false"
             Virtualize="false"
             @bind-RowsPerPage="_defaultPageSize"
             Height="calc(100vh - 300px)"
             Loading="@_loading"
             MultiSelection="true"
             @bind-SelectedItems="_selectedItems"
             ColumnResizeMode="ResizeMode.Column"
             Hover="true" @ref="_table">
    <ToolBarContent>
        <MudStack Row Spacing="0" Class="flex-grow-1" Justify="Justify.SpaceBetween">
            <MudStack Row AlignItems="AlignItems.Start">
                <MudIcon Icon="@Icons.Material.Filled.Window" Size="Size.Large" />
                <MudStack Spacing="0">
                    <MudText Typo="Typo.subtitle2" Class="mb-2">@L[_currentDto.GetClassDescription()]</MudText>
                    <MudEnumSelect Style="min-width:120px" TEnum="DocumentListView" ValueChanged="OnChangedListView" Value="Query.ListView" Dense="true" Label="@L["List View"]">
                    </MudEnumSelect>
                </MudStack>
            </MudStack>
            <MudStack Spacing="0" AlignItems="AlignItems.End">
                <MudToolBar Dense WrapContent="true" Class="py-1 px-0">
                    <MudButton 
                               Disabled="@_loading"
                               OnClick="@(() => OnRefresh())"
                               StartIcon="@Icons.Material.Outlined.Refresh" >
                        @ConstantString.Refresh
                    </MudButton>
                    @if (_canCreate)
                    {
                        <MudButton 
                                   StartIcon="@Icons.Material.Outlined.Camera"
                                   OnClick="OnCreate">
                            @L["Upload Pictures"]
                        </MudButton>
                    }
                    @if (_canDelete)
                    {
                        <MudButton 
                                   StartIcon="@Icons.Material.Outlined.Delete"
                                   Disabled="@(!(_selectedItems.Count > 0))"
                                   OnClick="OnDeleteChecked">
                            @ConstantString.Delete
                        </MudButton>
                    }
                </MudToolBar>
                <MudStack Row Spacing="1">
                    @if (_canSearch)
                    {
                        <MudTextField T="string" ValueChanged="@(s => OnSearch(s))" Value="@Query.Keyword" Placeholder="@ConstantString.Search" Adornment="Adornment.End"
                                      AdornmentIcon="@Icons.Material.Filled.Search" IconSize="Size.Small">
                        </MudTextField>
                    }
                </MudStack>
            </MudStack>
        </MudStack>


    </ToolBarContent>
    <Columns>
        <SelectColumn ShowInFooter="false"> </SelectColumn>
        <TemplateColumn HeaderStyle="width:60px" Title="@ConstantString.Actions" Sortable="false">
            <CellTemplate>
                @if (_canEdit || _canDelete)
                {
                    <MudMenu Icon="@Icons.Material.Filled.Edit" Variant="Variant.Filled" Size="Size.Small"
                             Dense="true"
                             EndIcon="@Icons.Material.Filled.KeyboardArrowDown" IconColor="Color.Info" AnchorOrigin="Origin.CenterLeft">
                        @if (_canEdit)
                        {
                            <MudMenuItem OnClick="@(() => OnEdit(context.Item))">@ConstantString.Edit</MudMenuItem>
                        }
                        @if (_canDelete)
                        {
                            <MudMenuItem OnClick="@(() => OnDelete(context.Item))">@ConstantString.Delete</MudMenuItem>
                        }
                        @if (_canDownload)
                        {
                            <MudMenuItem Disabled="@_downloading" OnClick="@(() => OnDownload(context.Item))">@ConstantString.Download</MudMenuItem>
                        }
                    </MudMenu>
                }
                else
                {
                    <MudButton Variant="Variant.Filled"
                               StartIcon="@Icons.Material.Filled.DoNotTouch" IconColor="Color.Secondary" Size="Size.Small"
                               Color="Color.Surface">
                        @ConstantString.NoAllowed
                    </MudButton>
                }
            </CellTemplate>
        </TemplateColumn>
        <PropertyColumn Property="x => x.Title" Title="@L[_currentDto.GetMemberDescription(x => x.Title)]">
            <CellTemplate>
                <div class="d-flex flex-column">
                    <MudText >@context.Item.Title</MudText>
                    <MudText Typo="Typo.body2" Class="mud-text-secondary">@context.Item.Description</MudText>
                </div>
            </CellTemplate>
        </PropertyColumn>
        <PropertyColumn Property="x => x.Status" Title="@L[_currentDto.GetMemberDescription(x => x.Status)]">
            <CellTemplate>
                <div class="d-flex flex-column">
                    <div class="flex-grow-0">
                        @switch (context.Item.Status)
                        {
                            case JobStatus.Queueing:
                                <MudChip Variant="Variant.Outlined" Size="Size.Small" Color="Color.Default" Disabled="true">@context.Item.Status</MudChip>
                                break;
                            case JobStatus.Doing:
                                <MudChip Icon="@Icons.Material.Outlined.DocumentScanner" Variant="Variant.Outlined" Size="Size.Small" Color="Color.Info"> @context.Item.Status</MudChip>
                                break;
                            case JobStatus.Done:
                                <MudChip Icon="@Icons.Material.Filled.Done" Variant="Variant.Filled" Size="Size.Small" Color="Color.Success">@context.Item.Status</MudChip>
                                break;
                            default:
                                <MudChip Variant="Variant.Outlined" Size="Size.Small" Color="Color.Primary">@context.Item.Status</MudChip>
                                break;
                        }
                    </div>
                    <div class="flex-grow-0  mud-text-secondary">
                        <MudHighlighter Text="@context.Item.Content" HighlightedText="@_searchString" Class="mud-text-secondary"></MudHighlighter>
                    </div>
                </div>
            </CellTemplate>
        </PropertyColumn>
        <PropertyColumn Property="x => x.DocumentType" Title="@L[_currentDto.GetMemberDescription(x => x.DocumentType)]">
            <CellTemplate>
                <div class="d-flex flex-column">
                    <MudCheckBox Size="Size.Small" Label="@L[_currentDto.GetMemberDescription(x => x.IsPublic)]" Value="@context.Item.IsPublic" Disabled="true"></MudCheckBox>
                    <MudText Typo="Typo.body2" Class="mud-text-secondary">@context.Item.DocumentType</MudText>
                </div>
            </CellTemplate>
        </PropertyColumn>
        <PropertyColumn Property="x => x.CreatedByUser" Title="@L[_currentDto.GetMemberDescription(x => x.CreatedByUser)]">
            <CellTemplate>
                @if (UserProfile?.UserId == context.Item.CreatedByUser?.Id)
                {
                    <MudChip Icon="@Icons.Material.Filled.Person" Color="Color.Primary"> Me </MudChip>
                }
                else
                {
                    <div class="d-flex flex-column">
                        <MudText>@context.Item.CreatedByUser?.DisplayName</MudText>
                        <MudText Typo="Typo.body2" Class="mud-text-secondary">@context.Item.CreatedByUser?.Email</MudText>
                    </div>
                }
            </CellTemplate>
        </PropertyColumn>
        <PropertyColumn Property="x => x.TenantName" Title="@L[_currentDto.GetMemberDescription(x => x.TenantName)]">
            <CellTemplate>
                <div class="d-flex flex-column">
                    <MudText Typo="Typo.body2">@context.Item.TenantName</MudText>
                    <MudText Typo="Typo.body2" Class="mud-text-secondary">@context.Item.TenantId</MudText>
                </div>
            </CellTemplate>
        </PropertyColumn>
    </Columns>
    <NoRecordsContent>
        <MudText>@ConstantString.NoRecords</MudText>
    </NoRecordsContent>
    <LoadingContent>
        <MudText>@ConstantString.Loading</MudText>
    </LoadingContent>
    <PagerContent>
        <MudDataGridPager PageSizeOptions="@(new[] { 10, 15, 30, 50, 100, 500, 1000 })" />
    </PagerContent>
</MudDataGrid>


@code {
    [CascadingParameter] protected Task<AuthenticationState> AuthState { get; set; } = default!;
    [CascadingParameter] private UserProfile? UserProfile { get; set; }
    private string? Title { get; set; }

    private HashSet<DocumentDto> _selectedItems = new();
    private readonly DocumentDto _currentDto = new();
    private MudDataGrid<DocumentDto> _table = null!;
    private int _defaultPageSize = 15;
    private string _searchString = string.Empty;
    private bool _downloading;
    private bool _loading;

    private string _tenantId = string.Empty;
    private DocumentsWithPaginationQuery Query { get; set; } = default!;

    private bool _canSearch;
    private bool _canCreate;
    private bool _canEdit;
    private bool _canDelete;
    private bool _canImport;
    private bool _canExport;
    private bool _canDownload;

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        Title = L[_currentDto.GetClassDescription()];
        var state = await AuthState;
        _canCreate = (await AuthService.AuthorizeAsync(state.User, Permissions.Documents.Create)).Succeeded;
        _canSearch = (await AuthService.AuthorizeAsync(state.User, Permissions.Documents.Search)).Succeeded;
        _canEdit = (await AuthService.AuthorizeAsync(state.User, Permissions.Documents.Edit)).Succeeded;
        _canDelete = (await AuthService.AuthorizeAsync(state.User, Permissions.Documents.Delete)).Succeeded;
        _canImport = (await AuthService.AuthorizeAsync(state.User, Permissions.Documents.Import)).Succeeded;
        _canExport = (await AuthService.AuthorizeAsync(state.User, Permissions.Documents.Export)).Succeeded;
        _canDownload = (await AuthService.AuthorizeAsync(state.User, Permissions.Documents.Download)).Succeeded;
        Client.JobCompletedEvent += _client_JobCompleted;
        Client.JobStartedEvent += _client_JobStarted;
        await Client.StartAsync();
        Query = new DocumentsWithPaginationQuery { CurrentUser = UserProfile };
    }

    private void _client_JobCompleted(object? sender, JobCompletedEventArgs e)
    {
        InvokeAsync(async () =>
        {
            await _table.ReloadServerData();
            if (e.Message.StartsWith("Error"))
            {
                Snackbar.Add(string.Format(L["{0}"], e.Id), Severity.Error);
            }
            else
            {
                Snackbar.Add(string.Format(L["{0}: {1} recognize completed."], e.Id, e.Message), Severity.Success);
            }

        });
    }

    private void _client_JobStarted(object? sender, JobStartedEventArgs e)
    {
        InvokeAsync(async () =>
        {
            await _table.ReloadServerData();
            Snackbar.Add(string.Format(L["{0}: {1} job started."], e.Id, e.Message), Severity.Info);
        });
    }


    public void Dispose()
    {
        Client.JobCompletedEvent -= _client_JobCompleted;
        Client.JobStartedEvent -= _client_JobStarted;
    }

    private async Task<GridData<DocumentDto>> ServerReload(GridState<DocumentDto> state)
    {
        try
        {
            _loading = true;
            Query.Keyword = _searchString;
            Query.CurrentUser = UserProfile;
            Query.OrderBy = state.SortDefinitions.FirstOrDefault()?.SortBy ?? "Id";
            Query.SortDirection = state.SortDefinitions.FirstOrDefault() == null ? SortDirection.Descending.ToString() : state.SortDefinitions.First().Descending ? SortDirection.Descending.ToString() : SortDirection.Ascending.ToString();
            Query.PageNumber = state.Page + 1;
            Query.PageSize = state.PageSize;
            var result = await Mediator.Send(Query);
            return new GridData<DocumentDto> { TotalItems = result.TotalItems, Items = result.Items };
        }
        finally
        {
            _loading = false;
        }
    }

    private void OnFilterChanged(string s)
    {
        InvokeAsync(async () => { await _table.ReloadServerData(); });
    }

    private async Task OnChangedListView(DocumentListView listview)
    {
        Query.ListView = listview;
        await _table.ReloadServerData();
    }

    private async Task OnSearch(string text)
    {
        DocumentCacheKey.Refresh();
        _selectedItems = new HashSet<DocumentDto>();
        _searchString = text;
        await _table.ReloadServerData();
    }

    private async Task OnRefresh()
    {
        _selectedItems = new HashSet<DocumentDto>();
        _searchString = string.Empty;
        await _table.ReloadServerData();
    }

    private async Task OnCreate()
    {
        var command = new AddEditDocumentCommand { DocumentType = DocumentType.Document };
        var parameters = new DialogParameters<UploadFilesFormDialog>
        {
            { x => x.Model, command }
        };
        var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.Small, FullWidth = true };
        var dialog = await DialogService.ShowAsync<UploadFilesFormDialog>
            (L["Upload Pictures"], parameters, options);
        var state = await dialog.Result;
        if (state is not null && !state.Canceled)
        {
            await _table.ReloadServerData();
            Snackbar.Add(ConstantString.UploadSuccess, Severity.Info);
        }
    }

    private async Task OnEdit(DocumentDto dto)
    {
        var command = DocumentMapper.ToEditCommand(dto);
        var parameters = new DialogParameters<DocumentFormDialog>
        {
            { nameof(DocumentFormDialog.Model), command }
        };
        var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.Medium, FullWidth = true };
        var dialog = await DialogService.ShowAsync<DocumentFormDialog>(string.Format(ConstantString.EditTheItem, L["Document"]), parameters, options);


        var state = await dialog.Result;
        if (state is not null && !state.Canceled)
        {
            await _table.ReloadServerData();
        }
    }

    private async Task OnDelete(DocumentDto dto)
    {
        var command = new DeleteDocumentCommand(new[] { dto.Id });
        var contentText = string.Format(ConstantString.DeleteConfirmation, dto.Title);
        await DialogServiceHelper.ShowDeleteConfirmationDialogAsync(command, string.Format(ConstantString.DeleteTheItem, L["Document"]), contentText, async () =>
        {
            await InvokeAsync(async () =>
              {
                  await _table.ReloadServerData();
                  _selectedItems.Clear();
              });

        });
    }

    private async Task OnDeleteChecked()
    {
        var command = new DeleteDocumentCommand(_selectedItems.Select(x => x.Id).ToArray());
        var contentText = string.Format(ConstantString.DeleteConfirmWithSelected, _selectedItems.Count);
        await DialogServiceHelper.ShowDeleteConfirmationDialogAsync(command, string.Format(ConstantString.DeleteTheItem, L["Document"]), contentText, async () =>
        {
            await InvokeAsync(async () =>
        {
            await _table.ReloadServerData();
            _selectedItems.Clear();
        });
        });
    }

    private async Task OnDownload(DocumentDto dto)
    {
        try
        {
            _downloading = true;
            var file = await Mediator.Send(new GetFileStreamQuery(dto.Id));
            if (file.Item2 != null)
            {
                var result = await BlazorDownloadFileService.DownloadFile(file.Item1, file.Item2, "application/octet-stream");
            }
        }
        catch (Exception e)
        {
            Snackbar.Add($"{e.Message}", Severity.Error);
        }
        finally
        {
            _downloading = false;
        }
    }

}